//
//  RecommendViewController.swift
//  Spookiness
//
//  Created by 腾億 on 2017/12/6.
//  Copyright © 2017年 tml. All rights reserved.
//

import UIKit
import LLCycleScrollView
import SwiftyJSON
class RecommendViewController: BaseViewController {

    private var sexType: Int = UserDefaults.standard.integer(forKey: String.sexTypeKey)
    
    //数据源
    fileprivate var comicLists = [ComicListsModel]()
    fileprivate var galleryItems = [GalleryItemModel]()
    
    //轮播图
    fileprivate lazy var bannerView:LLCycleScrollView = {
        let bannerView = LLCycleScrollView()
        bannerView.backgroundColor = kRGBA(r: 242, g: 242, b: 242, a: 1)
        bannerView.autoScrollTimeInterval = 3//// 滚动间隔时间(默认为2秒)
        bannerView.placeHolderImage = #imageLiteral(resourceName: "normal_placeholder_h")//等待数据状态显示的占位图
        bannerView.coverImage = UIImage()//如果没有数据的时候，使用的封面图
        //设置PageControl的位置 (.left, .right 默认为.center)
        bannerView.pageControlPosition = .right
        bannerView.pageControlBottom = 20
        //文本区域背景色
        bannerView.titleBackgroundColor = UIColor.clear
        bannerView.lldidSelectItemAtIndex = didSelectBanner(index:)
        return bannerView
    }()
    
    //角色切换
    fileprivate lazy var sexTypeButton: UIButton = {
       let button = UIButton(type: .custom)
        button.setTitleColor(UIColor.black, for: .normal)
        button.addTarget(self, action: #selector(changeSex), for: .touchUpInside)
        return button
    }()
    
    //collectionView
    fileprivate lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 5
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.alwaysBounceVertical = true
        collectionView.contentInset = UIEdgeInsetsMake(kSCREEN_WIDTH * 0.467, 0, 0, 0)
        collectionView.scrollIndicatorInsets = collectionView.contentInset
        collectionView.register(RecommendTypeCell.self, forCellWithReuseIdentifier: "RecommendTypeCell")
        collectionView.register(RecommendComicCell.self, forCellWithReuseIdentifier: "RecommendComicCell")
        collectionView.register(RecommentComicHead.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "RecommentComicHead")
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footView")
        collectionView.refrshHead = RefreshGifHeader {
            self.loadData(false)
        }
        return collectionView
    }()
    
    @objc fileprivate func changeSex() {
        
    }
    
    fileprivate func didSelectBanner(index: NSInteger) {
        let item = galleryItems[index]
        if item.linkType == 2 {
            guard let url: String = item.ext.flatMap({ return $0.key == "url" ? $0.val : nil }).joined() else { return }
            let vc = WebViewController(url: url)
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        }else {
            guard let comicIdString: String = item.ext.flatMap({ return $0.key == "comicId" ? $0.val : nil }).joined(),
                let comicId = Int(comicIdString) else { return }
            let vc = ComicsDetailViewController(comicid: comicId)
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    fileprivate func loadData(_ changeSex: Bool) {
        if changeSex {
            sexType = 3 - sexType
            UserDefaults.standard.set(sexType, forKey: String.sexTypeKey)
            UserDefaults.standard.synchronize()
        }
        NetworkTool.loadHomeRecommendData(sexType: sexType) {[weak self] (recommendModel) in
            for comics in recommendModel.comicLists {
                self?.comicLists.append(comics)
            }
            
            for gallery in recommendModel.galleryItems {
                self?.galleryItems.append(gallery)
            }
            
            self?.sexTypeButton.setImage(UIImage(named: self?.sexType == 1 ? "gender_male" : "gender_female"),
                                         for: .normal)
            self?.collectionView.refrshHead.endRefreshing()
            self?.collectionView.reloadData()
            self?.bannerView.imagePaths = self?.galleryItems.map({ (galleryModel: GalleryItemModel) -> String in
                galleryModel.cover!
            }) ?? []
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        loadData(false)
        setUpUISnap()
    }
    //布局
    fileprivate func setUpUISnap() {
        self.view.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(self.view.snp.bottom).offset(-2 * kTabbarHeight)
        }
        self.view.addSubview(self.bannerView)
        self.bannerView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(kSCREEN_WIDTH * 0.467)
        }
        self.view.addSubview(self.sexTypeButton)
        self.sexTypeButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(60)
            make.bottom.equalTo(self.view.snp.bottom).offset(-(2*kTabbarHeight + 20))
            make.right.equalTo(self.view.snp.right).offset(0)
        }
        
    }

}

extension RecommendViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.comicLists.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let comicList = comicLists[section]
        return comicList.comics.takeMax(4).count
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionElementKindSectionHeader {
            let head = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "RecommentComicHead", for: indexPath) as! RecommentComicHead
            let comicList = self.comicLists[indexPath.section]
            head.iocnView.kf.setImage(urlString: comicList.newTitleIconUrl)
            head.titleLable.text = comicList.itemTitle
            return head
        }else  {
            let foot = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footView", for: indexPath)
            foot.backgroundColor = kRGBA(r: 242, g: 242, b: 242, a: 1)
            return foot
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let comicList = comicLists[section]
        return comicList.itemTitle?.count ?? 0 > 0 ? CGSize(width: kSCREEN_WIDTH, height: 44) : CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return comicLists.count - 1 != section ? CGSize(width: kSCREEN_WIDTH, height: 10) : CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let comicList = comicLists[indexPath.section]
        if comicList.comicType == 11 {
            let width = floor((kSCREEN_WIDTH - 15.0) / 4.0)
            return CGSize(width: width, height: 80)
        }else {
            if comicList.comicType == 5 {
                let width = floor((kSCREEN_WIDTH - 5.0) / 2.0)
                return CGSize(width: width, height: 120)
            } else {
                let count = comicList.comics.takeMax(4).count
                let warp = count % 2 + 2
                let width = floor((kSCREEN_WIDTH - CGFloat(warp - 1) * 5.0) / CGFloat(warp))
                return CGSize(width: width, height: CGFloat(warp * 80))
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let comicList = comicLists[indexPath.section]
        if comicList.comicType == 11 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecommendTypeCell", for: indexPath) as! RecommendTypeCell
            cell.typeModel = comicList.comics[indexPath.row]
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecommendComicCell", for: indexPath) as! RecommendComicCell
            if comicList.comicType == 5 {
                cell.style = .none
            }else {
                cell.style = .withTitleAndDesc
            }
            cell.model = comicList.comics[indexPath.row]
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let comicList = comicLists[indexPath.section]
        guard let item:ComicsModel = comicList.comics[indexPath.row] else {
            return
        }
        
        if comicList.comicType == 11 {
            let vc = HomeComicsListViewController(argCon: item.argCon, argName: item.argName ?? "", argValue: item.argValue)
            vc.hidesBottomBarWhenPushed = true
            vc.title = item.name
            self.navigationController?.pushViewController(vc, animated: true)
        }else {
            if item.linkType == 2 {
                guard let url: String = item.ext.flatMap({ return $0.key == "url" ? $0.val : nil }).joined() else { return }
                let vc = WebViewController(url: url)
                vc.hidesBottomBarWhenPushed = true
                navigationController?.pushViewController(vc, animated: true)
            } else {
                let vc = ComicsDetailViewController(comicid: item.comicId)
                vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
            
        }
        
    }
    
}

extension RecommendViewController {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == collectionView {
            bannerView.snp.updateConstraints{ $0.top.equalToSuperview().offset(min(0, -(scrollView.contentOffset.y + scrollView.contentInset.top))) }
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if scrollView == collectionView {
            UIView.animate(withDuration: 0.5, animations: {
                self.sexTypeButton.transform = CGAffineTransform(translationX: 50, y: 0)
            })
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView == collectionView {
            UIView.animate(withDuration: 0.5, animations: {
                self.sexTypeButton.transform = CGAffineTransform.identity
            })
        }
    }
}



